<template>
	<view class="container">
		<image class="bgColor" src="http://shejihm.oss-cn-beijing.aliyuncs.com/202403301918201711797500692c12ed02b.png" mode=""></image>
		<u-navbar
			title="首页" 
			:isBack="false"
			:background="{ background: 'rgba(0,0,0,0)' }" 
			:titleColor="titleStyle"
		></u-navbar>
<!-- 		<scroll-view
			scroll-y="true"  
			style="position: absolute; height:100vh; top: 0; right: 0; bottom: 0; left: 0;"
			@scroll="pageScroll"
			:throttle="false"
		> -->
			<z-paging
				ref="paging"
				v-model="recommendList"
				@query="(pageNo, pageSize)=>{ getBannerList();  getRecommendList(pageNo, pageSize)  }" 
				auto-show-back-to-top 
				refresher-theme-style="white"
			>
				<template v-slot:top>
					<view :style="{'margin-top': sHeight}"></view>
				</template>
				<!-- <HomeSkeleton v-if="false"></HomeSkeleton> -->
				<view class="content" style="padding-top: 20rpx;">
				
					<!-- 轮播 -->
					<u-swiper
						:list="bannerList"
						mode="rect"
						height="308"
						bg-color="rgba(0,0,0,0)"
						@click="handleClickBanner"
					></u-swiper>
					<!-- <u-button
						@click="()=>{testWatch+=1}"
					>{{testWatch}}</u-button>
					<u-button
						@click="()=>{testWatch2+=1}"
					>{{testWatch2}}</u-button> -->
					<!-- 金刚区 -->
					<view class="width100" style="margin-top: 40rpx;">
						<u-grid :col="4" :border="false" :hover-class="{}">
							<u-grid-item v-for="item in menuList" :key="item.id" @tap.stop="handleClickMenu(item.id)">
								<image class="link-image" :src="item.image"></image>
								<view class="grid-text">{{item.name}}</view>
							</u-grid-item>
						</u-grid>
					</view>
					<!-- 邀请 -->
					<view class="width100" @tap.stop="$u.throttle(toInvite, 1000)">
						<image 
							class="invite" 
							:src="indexImages.find(item=>item.code=='invite_image')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/2024040817153017125677303269dff7666.png'"
						></image>
					</view>
					<!-- 推荐作品 -->
					<view class="recommendText width100">推荐作品</view>
					<view class="goodsWrapper width100">
						<view class="goodsItem" v-for="item in recommendList" :key="item.id" @tap="ToDetail(item.id)">
							<image :lazy-load="true" style="width: 100%;" :src="item.image" mode="scaleToFill"></image>
							<view class="item-bottom">
								<view class="title ellipsis2">{{item.name}}</view>
								<view class="info">
									<image class="avatar" src="http://shejihm.oss-cn-beijing.aliyuncs.com/202404081716451712567805660400ddad8.png" mode="scaleToFill"></image>
									<text class="nickname">设计很忙官方</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</z-paging>
		<!-- </scroll-view> -->
		<u-modal 
			v-model="showWarning" 
			content="非合伙人不可进入" 
			@confirm="toApply"
			:show-cancel-button="true"
			confirmText="去申请"
		></u-modal>
		<!-- 海报 -->
		<uni-popup
			 type="center" 
			 style="top: 35rpx;"
			 ref="posterImg" 
			 :maskClick="false"
		>
			<view class="wrapper">
				<view style="width: 100%; text-align: right;">
					<image @tap.stop="close()" class="wrapper_closeBtn" src="../../static/images/close_btn.png" mode=""></image>
				</view>
				<image class="painterImg" :src="picture"></image>
				<view class="wrapper_save flex justify-center align-center" @click="handleSaveImage">保存图片</view>
			</view>
		</uni-popup>

		<l-painter
			:css="`width: 600rpx;height:950rpx;background-image:url(${indexImages.find(item=>item.code=='poster_image')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/202404080940061712540406528c0c6b6e2.png'});`"
			@fail="fail"
			pathType="url"
			ref="poster"
			custom-style="position: fixed; left: 200%"
		>
			<l-painter-image
				src="http://shejihm.oss-cn-beijing.aliyuncs.com/202404081716451712567805660400ddad8.png"
				css="width: 85rpx;height:85rpx;position:absolute;bottom:32rpx;left:24rpx;border-radius:50%;"
			/>
			<l-painter-text
			  text="设计很忙官方"
			  css="font-size:30rpx;font-weight:bold;color:#333;position:absolute;bottom:75rpx;left:130rpx;"
			/>
			<l-painter-text
			  text="邀请用户来注册"
			  css="font-size:22rpx;font-weight:400;color:#999;position:absolute;bottom:35rpx;left:130rpx;"
			/>
			<l-painter-image :src="invitationCode" css="width: 140rpx;height:140rpx;position:absolute;bottom:5rpx;right:15rpx;border-radius:10rpx;" />
		</l-painter>
		
		<u-modal
			v-model="conShow" 
			content="确认打开客服会话？" 
			@confirm="openCustomLink()"
			:show-cancel-button="true"
			confirmText="确认"
			cancelText="取消"
		></u-modal>
	</view>
</template>

<script setup>
	import { getCurrentInstance,reactive,ref, watch, computed } from "vue";
	import { onShow,onLoad,onHide,onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import HomeSkeleton from '../../components/PageSkeleton/home.vue'
	import {useMainStore} from '@/store/index.js'
	const { proxy } = getCurrentInstance()
	const loading = ref(true)
	const showWarning = ref(false)
	const bgColor = ref('rgba(0,0,0,0)')
	const titleStyle = ref('#fff')
	const leftColor = ref('#fff')
	const posterShow = ref(false)
	const picture = ref('')//生成的海报图片
	const invitationCode = ref('')  //二维码地址
	let bannerList = ref([])
	let recommendList = ref([])
	const sHeight = ref('')
	const mainStore = useMainStore()
	const link = ref('')
	const indexImages = ref([])
	const conShow = ref(false)
	let menuList = computed(() => [
		{id: 1, image:indexImages.value.find(item=>item.code=='logo_1')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/202404291123421714361022004cac05e55.png', name:'画施工图'},
		{id: 2, image:indexImages.value.find(item=>item.code=='logo_2')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/2024042911234917143610294717be0eee7.png', name:'画效果图'},
		{id: 3, image:indexImages.value.find(item=>item.code=='logo_3')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/202404291123561714361036535e205e53f.png', name:'我们是谁'},
		{id: 4, image:indexImages.value.find(item=>item.code=='logo_4')?.images || 'http://shejihm.oss-cn-beijing.aliyuncs.com/202404291124021714361042667175b0b85.png', name:'画图咨询'},
	])
	// const testWatch = ref('t')  //用来测试vue3的watch
	// const testWatch2 = ref(1)
	/*
	import {useMainStore} from '@/store/index.js'
	const mainStore = useMainStore()
	mainStore.handleGetUserInfo()
	mainStore.userInfo
	*/
	// watch(
	// 	[
	// 		testWatch,
	// 		testWatch2
	// 	],
	// 	([newValue, newValue2], [oldValue, oldValue2])=>{
	// 		console.log('1',newValue, newValue2)
	// 		console.log('2',oldValue, oldValue2)
	// 	},
	// 	{
	// 		deep:true
	// 	}
	// )
	
	// // 自定义此页面的转发给好友(已经有全局的分享方法，此处会覆盖全局)
	// onShareAppMessage(res) {
	// 	return {
	// 		title: '分享我的商品（' + this.message.goodsName + '）',
	// 		path: '/pagesA/ordersDetail/index?id=' + this.options.id + '&title=' + this.options.title + '&status=' + this.options.status + '&currentTimeFlag=' + this.options.currentTimeFlag + '&back=' + 1,
	// 		imageUrl: this.list[0]
	// 	};
	// },
	// // 自定义页面的分享到朋友圈
	// onShareTimeline(res) {
	// 	return {
	// 		title: '分享我的商品（' + this.message.goodsName + '）',
	// 		query: `id=${this.options.id}&title=${this.options.title}&status=${this.options.status}&currentTimeFlag=${this.options.currentTimeFlag}&back=1`,
	// 		imageUrl: this.list[0]
	// 	};
	// },
	// 自定义此页面的转发给好友(已经有全局的分享方法，此处会覆盖全局)
	onShareAppMessage(()=>{
			return {
				title: '设计很忙',
				// path: '/pagesA/washBeauty/MaintenanceDetail?id=' + this.options.id + '&back=' + 1 + '&storeId=' + this.options.storeId,
				// query: `id=${this.options.id}&storeId=${this.options.storeId}&back=1`,
				// imageUrl: this.Detail.goodsLogo
			};
		
	})
	// 自定义页面的分享到朋友圈
	onShareTimeline(()=>{
		return {
			title: '设计很忙',
			// query: `id=${this.options.id}&title=${this.options.title}&status=${this.options.status}&currentTimeFlag=${this.options.currentTimeFlag}&back=1`,
			// imageUrl: this.list[0]
		};
	})
	onLoad((option)=>{
		getStatusHeight() //适配顶部高度
		// 从字典获取数据
		proxy.api.system({code: 'index_images'}).then(res=>{
			console.log('图片字典数据---', res.data.data)
			indexImages.value = res.data.data
		})
		getLink()
		uni.$on('handle_apply', ()=>{
			mainStore.handleGetUserInfo()
			proxy.tui.toast('申请成功')
		})
		// Promise.all([
		// getBannerList()
		// 	getRecommendList(),
		// ]).then(()=>{
		// 	loading.value = false
		// })
		// 判断用户是否是通过扫码进入的
		// let optCopy = getQueryFromOption(option);
		console.log('扫码分享的参数', option);
		uni.setStorageSync('SCENE', option.scene);
	})
	// 获取客服链接
	function getLink(){
		proxy.api.system({code:'kf_link'}).then(res=>{
			link.value = res?.data?.data.find(item=>item.code=='order_link')?.dictValue
		})
	}
	// 去申请合伙人
	function toApply(){
		uni.navigateTo({
			url:`/pages/my/apply`
		})
	}
	function handleSaveImage() {
		uni.authorize({
			scope: 'scope.writePhotosAlbum',  //保存到相册授权
			success: a => {
				uni.saveImageToPhotosAlbum({
					filePath: picture.value,
					success: () => {
						proxy.tui.toast('保存到相册成功');
					},
					fail: err => {
						proxy.tui.toast('保存到相册失败');
					}
				});
			},
			fail: a => {
				uni.showModal({
					title: '提示',
					content: '授权失败，是否前往设置开启相关权限',
					success: res => {
						if (res.confirm) {
							wx.openSetting();
						} else if (res.cancel) {
							proxy.tui.toast('授权失败');
						}
					}
				});
			}
		});
	}
	function getStatusHeight() {
		sHeight.value = uni.getSystemInfoSync().statusBarHeight + 54 + 'px';
	}
	// 跳转到作品详情
	function ToDetail(id){
		uni.navigateTo({
			url:`/pages/menusByIndex/compositionDetail?id=${id}`
		})
	}
	// 计算顶部tabbar
	function pageScroll(e){
		console.log('执行了滑动', e.detail.scrollTop)
		bgColor.value = `rgba(255, 255, 255, ${e.detail.scrollTop<5 ? 0 : (e.detail.scrollTop>44 ? 50 : e.detail.scrollTop)/50})`;
		titleStyle.value = e.detail.scrollTop>25 ? '#000' : '#fff';
		leftColor.value = e.detail.scrollTop>25 ? '#000' : '#fff';
		console.log('bgColor',bgColor.value)
		console.log('titleStyle',titleStyle.value)
		console.log('leftColor',leftColor.value)
	}
	
	// 扫码判断
	function getQueryFromOption(option) {
		if (option.q) {
			const url = decodeURIComponent(option.q);
			const search = url.split('?')[1];
			return { option, source: 'qrcode' /* 来源二维码扫码 */, ...parseQuery(search) };
		}
		return option;
	}
	// 获取轮播图列表
	function getBannerList(){
		return new Promise((resolve, inject)=>{
			proxy.api.bannerList().then(res=>{
				bannerList.value = res.data.data.map(item=>{
					return {
						image: item.image,
						content: item.content,
					}
				})
				resolve()
			}).catch(err=>{
				inject(err)
			})
		})
	}
	function toInvite(){
		if(proxy.utils.isLogin()){
			uni.showLoading({
				title: '分享海报生成中'
			});
			let alreadyCode = uni.getStorageSync("USER_INFO").invitationCodeImage
			if(alreadyCode){
				invitationCode.value = alreadyCode
				proxy.$nextTick(()=>{
					proxy.$refs.poster.canvasToTempFilePathSync({
						fileType: 'png',
						quality: 1,
						success: res => {
							console.log(res);
							uni.hideLoading();
							picture.value = res.tempFilePath;
							proxy.$refs.posterImg.open();
						},
						fail(e) {}
					});
				})
			}else{
				proxy.api.generateInvitationCode({}).then(res=>{
					invitationCode.value = res.data.data
					mainStore.handleGetUserInfo()
					proxy.$nextTick(()=>{
						proxy.$refs.poster.canvasToTempFilePathSync({
							fileType: 'png',
							quality: 1,
							success: res => {
								console.log(res);
								uni.hideLoading();
								picture.value = res.tempFilePath;
								proxy.$refs.posterImg.open();
							},
							fail(e) {}
						});
					})
				})
			}
		}
	}
	// 获取推荐作品列表
	function getRecommendList(pageNo, pageSize){  
		// return new Promise((resolve, inject)=>{
			let query = {
				pageNo: pageNo,
				pageSize
			}
			proxy.api.recommendWorksList(query).then(res=>{
				// recommendList.value = res.data.rows
				proxy.$refs.paging.complete(res.data.data.records);
				loading.value = false
				console.log('loading', loading)
				// resolve()
			}).catch(err=>{
				// inject(err)
			})
		// })
	}
	// 轮播图点击事件
	function handleClickBanner(index){
		let content = Array.isArray(bannerList.value)&&bannerList.value.length ? bannerList.value[index].content : ''
		console.log(index, content)
		let query = {
			content: content
		}
		uni.navigateTo({
			url:`/pages/index/bannerDetail?query=${encodeURIComponent(JSON.stringify(query))}`
		})
	}
	
	function close(){
		proxy.$refs.posterImg.close();
	}
	
	// 画图咨询 打开客服链接
	function openCustomLink(){
		if(proxy.utils.isLogin()){
			if(!link.value){
				proxy.tui.toast('客服链接未配置')
				return
			}
			wx.openCustomerServiceChat({
				extInfo:{
					url:link.value
				},
				corpId: 'ww591e8d883d4208fd', // 如果需要的话  
				success(res) {
				 proxy.tui.toast('客服会话已成功打开');  
				},  
				fail(err) {
					console.log(err)
				 proxy.tui.toast('打开客服会话失败');  
				}  
			});  
		}
	}
	
	function handleClickMenu(id){
		if(id==1){
			uni.navigateTo({ // 画施工图
				url:`/pages/menusByIndex/compositionStore?type=1`
			})
		}else if(id==2){
			uni.navigateTo({ // 画效果图
				url:`/pages/menusByIndex/compositionStore?type=2`
			})
		}else if(id==3){
			uni.navigateTo({ // 公司介绍（我们是谁）
				url:`/pages/agreement/agreement?pageTitle=我们是谁&code=company_info`
			})
		}else if(id==4){
			// openCustomLink()
			conShow.value = true
			// if(proxy.utils.isLogin()){
			// 	if(uni.getStorageSync('USER_INFO').isPartner!=2){
			// 		showWarning.value = true
			// 		return
			// 	}
			// 	uni.navigateTo({ // 排行榜
			// 		url:`/pages/menusByIndex/randingList`
			// 	})
			// }
		}
	}
</script>

<style lang="scss">
	::v-deep .u-swiper-indicator{
		bottom: -24rpx !important;
	}
	::v-deep swiper{
		border-radius: 10rpx !important;
		overflow: hidden;
	}
	::v-deep .u-swiper-image{
		box-shadow: 0rpx 6rpx 16rpx rgba(26,117,253,0.14) !important;
	}
	::v-deep .u-swiper-wrap{
		overflow: visible !important;
	}
	::v-deep .u-indicator-item-rect {
		background-color: #D1D1D1 !important;
		border-radius: 5rpx !important;
		width: 32rpx !important;
		height: 6rpx !important;
	}
	::v-deep .u-indicator-item-rect-active {
		background-color: $uni-color-primary !important;
		border-radius: 5rpx !important;
		width: 32rpx !important;
		height: 6rpx !important;
	}
	::v-deep .u-grid-item-box{
		padding: 18rpx 0 10rpx 0 !important;
	}
	::v-deep .uni-popup__wrapper-box{
		position: relative;
		top: 35rpx;
	}
	.bgColor {
		width: 100vw;
		height: 362rpx;
		// background: linear-gradient(180deg, #3a8ad9 0%, #3379c0 40%, #4a86c1 60%, #DCEEFF 100%);
		position: relative;
		z-index: -99;
	}
	.width100{
		background-color: #fff;
		width: 750rpx;
		margin-left: -20rpx;
		padding:0 20rpx;
		
	}
	.painterImg{
		width: 600rpx;
		height: 950rpx;
	}
	.wrapper{
		&_closeBtn{
			width: 66rpx;
			height: 66rpx;
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			z-index: 999;
		}
		&_bgImage{
			width: 600rpx;
			height: 950rpx;
		}
		&_active{
			width: 600rpx;
			box-sizing: border-box;
			padding: 0 24rpx;
			position: absolute;
			top:740rpx;
			&>text:first-child{
				@include str(28rpx, bold, #333);
				line-height: 40rpx;
			}
			&>text:last-child{
				@include str(24rpx, 400, #333);
				line-height: 33rpx;
			}
		}
		&_save{
			width: 100%;
			height: 88rpx;
			margin-top: 34rpx;
			background: linear-gradient(90deg, #3B8CDC 0%, #2D6BA9 100%);
			border-radius: 16rpx;
			@include str(30rpx, bold, #fff)
		}
	}
	.container{
		height: 100vh;
		overflow-y: scroll;
		.content{
			width: calc(100vw - 40rpx);
			margin-left: 20rpx;
			position: relative;
			// margin-top: 106rpx;
			// 金刚区
			.link-image{
				width: 94rpx;
				height: 94rpx;
				border-radius: 36rpx;
			}
			.grid-text {
				font-family: 'PingFang SC';
				font-weight: 500;
				font-size: 26rpx;
				color: #666666;
				line-height: 37rpx;
				margin-top: 11rpx;
			}
			// 邀请
			.invite{
				width: 100%;
				height: 168rpx;
			}
			// 推荐作品
			.recommendText{
				font-family: 'Alibaba PuHuiTi 2.0';
				font-weight: bolder;
				font-size: 36rpx;
				color: #333333;
				line-height: 122rpx;
			}
			.goodsWrapper{
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
				flex-wrap: wrap;
				.goodsItem{
					width: 340rpx;
					border-radius: 12rpx;
					overflow: hidden;
					margin-bottom: 40rpx;
					box-shadow: 0px 0px 9rpx 0.5rpx rgba(0, 0, 0, 0.1);
					&>image{
						height: 340rpx;
					}
					.item-bottom{
						padding: 0rpx 16rpx 22rpx 16rpx;
						.title{
							font-family: 'PingFang SC';
							font-weight: bold;
							font-size: 28rpx;
							color: #333333;
							min-height: 84rpx;
							line-height: 40rpx;
							margin-bottom: 5rpx;
						}
						.info{
							display: flex;
							justify-content: flex-start;
							line-height: 42rpx;
							.avatar{
								width: 42rpx;
								height: 42rpx;
								border-radius: 50%;
								overflow: hidden;
							}
							.nickname{
								font-family: 'PingFang SC';
								font-weight: 500;
								font-size: 24rpx;
								color: #999999;
								line-height: 33rpx;
								margin-left: 10rpx;
								position: relative;
								top: 4rpx;
							}
						}
					}
					
				}
			}
		}
	}

</style>